package com.ibm.productivity.tools.blogplugin.impl;

import java.net.MalformedURLException;
import java.net.URL;
import java.util.Map;

import org.apache.xmlrpc.XmlRpcException;
import org.apache.xmlrpc.client.XmlRpcClient;
import org.apache.xmlrpc.client.XmlRpcClientConfigImpl;

import com.ibm.productivity.tools.blogplugin.meta.IBlog;
import com.ibm.productivity.tools.blogplugin.meta.IBlogAccount;

public class MsnBlogAccount implements IBlogAccount {
	private static final String loginUrl = "blogger.getUsersBlogs";
	private static final String apiUrl = "https://storage.msn.com/storageservice/MetaWeblog.rpc";
	public static final String appKey = "symphony";
	private String[] blogid;
	private String[] blogUrl; 
	private String[] blogName;
	private int blogCount;
	private IBlog [] blogs;
	public XmlRpcClient client;
	String username;
	String password;

	public MsnBlogAccount() {
		try {
			XmlRpcClientConfigImpl config = new XmlRpcClientConfigImpl();
			config.setServerURL(new URL(apiUrl));
			client = new XmlRpcClient();
			client.setConfig(config);
			client.setTypeFactory(new MsnTypeFactory(client));
		} catch (MalformedURLException e) {
			// won't be here except the appUrl is a wrong URL format.
			System.out.println("apiUrl format is wrong:"+apiUrl);
			e.printStackTrace();
		}
	}

	public IBlog getBlog(int index) {
		if (index <0 && index >=blogCount)  
			return null;
		return 
			blogs[index];
	}

	public int getBlogCount() {
		return blogCount;
	}

	@SuppressWarnings("unchecked")
	public boolean login(String username, String password) {
		try {
			Object[] blogInfo = (Object[]) client.execute(
					loginUrl, new Object[]{appKey, username, password}
					);
			this.username = username;
			this.password = password;
			blogCount = blogInfo.length;
			blogid = new String[blogCount];
			blogUrl = new String[blogCount];
			blogName = new String[blogCount];
			blogs = new MsnBlog[blogCount];
			for (int i=0; i<blogCount; ++i) {				
				if (blogInfo[i] instanceof Map ) {
					Map<String, String> blog = (Map<String, String>)blogInfo[i];				
					blogid[i] = blog.get("blogid");
					blogUrl[i] = blog.get("url");
					blogName[i] = blog.get("blogName");
					blogs[i] = new MsnBlog(blogid[i], blogUrl[i], blogName[i], this);
				}
			}
		} catch (XmlRpcException e) {
			e.printStackTrace();
			return false;
		}
		return true;
	}

	public boolean logout() {
		return true;
	}

}
